package handler

import (
	"strconv"
	"time"

	"github.com/gin-gonic/gin"

	"hrms-api/model"
)

// CreateTraining 创建培训
func CreateTraining(c *gin.Context) {
	var training model.Training
	if err := c.ShouldBindJSON(&training); err != nil {
		BadRequest(c, "Invalid request payload")
		return
	}

	if err := model.DB.Create(&training).Error; err != nil {
		InternalServerError(c, err.Error())
		return
	}

	Success(c, training)
}

// UpdateTraining 更新培训信息
func UpdateTraining(c *gin.Context) {
	id := c.Param("id")
	var training model.Training

	if err := model.DB.First(&training, id).Error; err != nil {
		NotFound(c, "Training not found")
		return
	}

	if err := c.ShouldBindJSON(&training); err != nil {
		BadRequest(c, "Invalid request payload")
		return
	}

	if err := model.DB.Save(&training).Error; err != nil {
		InternalServerError(c, err.Error())
		return
	}

	Success(c, training)
}

// GetTrainingDetail 获取培训详情
func GetTrainingDetail(c *gin.Context) {
	id := c.Param("id")
	var training model.Training

	if err := model.DB.First(&training, id).Error; err != nil {
		NotFound(c, "Training not found")
		return
	}

	Success(c, training)
}

// GetTrainings 获取培训列表
func ListTrainings(c *gin.Context) {
	var trainings []model.Training
	query := model.DB.Model(&model.Training{})

	// 支持按状态筛选
	if status := c.Query("status"); status != "" {
		query = query.Where("status = ?", status)
	}

	// 支持按时间范围筛选
	if startTime := c.Query("start_time"); startTime != "" {
		query = query.Where("start_time >= ?", startTime)
	}
	if endTime := c.Query("end_time"); endTime != "" {
		query = query.Where("end_time <= ?", endTime)
	}

	// 分页处理
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "10"))
	query = query.Offset((page - 1) * pageSize).Limit(pageSize)

	if err := query.Find(&trainings).Error; err != nil {
		InternalServerError(c, err.Error())
		return
	}

	// 获取总数用于分页
	var total int64
	model.DB.Model(&model.Training{}).Count(&total)

	Success(c, gin.H{
		"list":      trainings,
		"total":     total,
		"page":      page,
		"page_size": pageSize,
	})
}

// DeleteTraining 删除培训
func DeleteTraining(c *gin.Context) {
	id := c.Param("id")
	var training model.Training

	if err := model.DB.First(&training, id).Error; err != nil {
		NotFound(c, "Training not found")
		return
	}

	if err := model.DB.Delete(&training).Error; err != nil {
		InternalServerError(c, err.Error())
		return
	}

	Success(c, nil)
}

// EnrollTraining 报名培训
func EnrollTraining(c *gin.Context) {
	trainingID := c.Param("id")
	userID := c.GetUint("user_id")

	// 检查培训是否存在
	var training model.Training
	if err := model.DB.First(&training, trainingID).Error; err != nil {
		NotFound(c, "Training not found")
		return
	}

	// 由于我们删除了TrainingRecord模型，这里只模拟报名成功
	// 在实际应用中应该在数据库中记录报名信息

	Success(c, gin.H{
		"training_id": training.ID,
		"user_id":     userID,
		"enrolled_at": time.Now(),
		"status":      "enrolled",
		"message":     "报名成功",
	})
}

// PublishTraining 发布培训
func PublishTraining(c *gin.Context) {
	id := c.Param("id")
	var training model.Training

	if err := model.DB.First(&training, id).Error; err != nil {
		NotFound(c, "Training not found")
		return
	}

	// 检查培训是否已发布
	if training.Status == "published" {
		BadRequest(c, "Training already published")
		return
	}

	// 更新状态为已发布
	training.Status = "published"
	if err := model.DB.Save(&training).Error; err != nil {
		InternalServerError(c, err.Error())
		return
	}

	Success(c, training)
}

// CancelTraining 取消培训
func CancelTraining(c *gin.Context) {
	id := c.Param("id")
	var training model.Training

	if err := model.DB.First(&training, id).Error; err != nil {
		NotFound(c, "Training not found")
		return
	}

	// 检查培训是否已取消
	if training.Status == "canceled" {
		BadRequest(c, "Training already canceled")
		return
	}

	// 检查培训是否已开始
	if training.StartTime.Before(time.Now()) {
		BadRequest(c, "Cannot cancel training after it started")
		return
	}

	// 更新状态为已取消
	training.Status = "canceled"
	if err := model.DB.Save(&training).Error; err != nil {
		InternalServerError(c, err.Error())
		return
	}

	Success(c, training)
}

// CancelEnrollment 取消报名
func CancelEnrollment(c *gin.Context) {
	id := c.Param("id")
	userID := c.GetUint("user_id")

	// 检查报名记录是否存在
	var record model.TrainingRecord
	if err := model.DB.Where("id = ? AND user_id = ?", id, userID).First(&record).Error; err != nil {
		NotFound(c, "Enrollment record not found")
		return
	}

	// 检查培训是否已经开始
	var training model.Training
	if err := model.DB.First(&training, record.TrainingID).Error; err != nil {
		InternalServerError(c, err.Error())
		return
	}

	if training.StartTime.Before(time.Now()) {
		BadRequest(c, "Cannot cancel enrollment after training started")
		return
	}

	// 删除报名记录
	if err := model.DB.Delete(&record).Error; err != nil {
		InternalServerError(c, err.Error())
		return
	}

	Success(c, nil)
}

// ListCourses 获取课程列表
func ListCourses(c *gin.Context) {
	trainingID := c.Param("id")
	var courses []model.TrainingCourse

	if err := model.DB.Where("training_id = ?", trainingID).Find(&courses).Error; err != nil {
		InternalServerError(c, err.Error())
		return
	}

	Success(c, courses)
}

// AddCourse 添加课程
func AddCourse(c *gin.Context) {
	trainingID := c.Param("id")
	var course model.TrainingCourse

	if err := c.ShouldBindJSON(&course); err != nil {
		BadRequest(c, "Invalid request payload")
		return
	}

	// 设置培训ID
	trainingIDUint, err := strconv.ParseUint(trainingID, 10, 32)
	if err != nil {
		BadRequest(c, "Invalid training ID")
		return
	}
	course.TrainingID = uint(trainingIDUint)

	if err := model.DB.Create(&course).Error; err != nil {
		InternalServerError(c, err.Error())
		return
	}

	Success(c, course)
}

// UpdateCourse 更新课程
func UpdateCourse(c *gin.Context) {
	trainingID := c.Param("id")
	courseID := c.Param("course_id")
	var course model.TrainingCourse

	// 检查课程是否存在
	if err := model.DB.Where("id = ? AND training_id = ?", courseID, trainingID).First(&course).Error; err != nil {
		NotFound(c, "Course not found")
		return
	}

	if err := c.ShouldBindJSON(&course); err != nil {
		BadRequest(c, "Invalid request payload")
		return
	}

	if err := model.DB.Save(&course).Error; err != nil {
		InternalServerError(c, err.Error())
		return
	}

	Success(c, course)
}

// GetMyEnrollments 获取我的报名记录
func GetMyEnrollments(c *gin.Context) {
	userID := c.GetUint("user_id")

	var records []model.TrainingRecord
	if err := model.DB.Where("user_id = ?", userID).Preload("Training").Find(&records).Error; err != nil {
		InternalServerError(c, err.Error())
		return
	}

	Success(c, records)
}

// MarkCompleted 标记培训完成
func MarkCompleted(c *gin.Context) {
	id := c.Param("id")
	userID := c.GetUint("user_id")

	// 获取培训记录
	var record model.TrainingRecord
	if err := model.DB.Where("id = ? AND user_id = ?", id, userID).First(&record).Error; err != nil {
		NotFound(c, "Enrollment record not found")
		return
	}

	// 检查培训是否已完成
	if record.Status == "completed" {
		BadRequest(c, "Training already completed")
		return
	}

	// 更新状态为已完成
	record.Status = "completed"
	if err := model.DB.Save(&record).Error; err != nil {
		InternalServerError(c, err.Error())
		return
	}

	Success(c, record)
}
